'use strict';
const fs = require('mz/fs');
const path = require('path');
const pump = require('mz-modules/pump');

const Controller = require('egg').Controller;

class UploadController extends Controller {
//用户头像上传
async userAvatarUpload(){
    const { ctx } = this;
    const file = ctx.request.files[0];//接收文件
    if (!file) return ctx.throw(404);

    let user_id = this.ctx.cookies.get('userid',{
        maxAge: 10000 * 1000,
        httpOnly: false,
        overwrite: true,
        signed: false,
    });
    const filename = (user_id).toString() + (Date.parse(new Date())).toString() + path.extname(file.filename).toLowerCase();
    const targetPath = path.join(this.config.baseDir, `app/public/img`, filename);
    const source = fs.createReadStream(file.filepath);
    const target = fs.createWriteStream(targetPath);
    
    //上传图片到 public/avatar文件夹
    try {
        await pump(source, target);
        ctx.logger.warn('save %s to %s', file.filepath, targetPath);  
        //将图片url存入数据库
        let userAvatarPath=`/img/${filename}`;
        await this.app.model.User.update({
                imgurl:userAvatarPath
                }, {
                    where: {
                        id:user_id
                    }
                })
        //返回图片路径给前端image标签
        this.ctx.body=userAvatarPath        
        } finally {
        // delete those request tmp files
        await ctx.cleanupRequestFiles(); 
        }   
  }

    //群头像上传
    async groupAvatarUpload(){
        const { ctx } = this;
        const file = ctx.request.files[0];//接收文件
        if (!file) return ctx.throw(404);
        
        let user_id = this.ctx.cookies.get('userid',{
            maxAge: 10000 * 1000,
            httpOnly: false,
            overwrite: true,
            signed: false,
        });
        const filename = (user_id).toString() + (Date.parse(new Date())).toString() + path.extname(file.filename).toLowerCase();// path.extname返回图片拓展名（如jpg）
        const targetPath = path.join(this.config.baseDir, `app/public/img`, filename);
        const source = fs.createReadStream(file.filepath);
        const target = fs.createWriteStream(targetPath);
        
        //上传图片到 public/groupavatar文件夹
        try {
        await pump(source, target);
        ctx.logger.warn('save %s to %s', file.filepath, targetPath);  
        
        let groupAvatarPath=`/img/${filename}`;

        //返回图片路径给前端image标签
        this.ctx.body=groupAvatarPath

        } finally {
        // delete those request tmp files
        await ctx.cleanupRequestFiles(); 
        }

      
    }
}

module.exports = UploadController;
